// pages/biz/auctions/orderList/orderList.js
//2019.6.11更改，全部统一拿status去判断
// 订单列表、订单详情接口：status字段
// 1.显示活动未开始标签
// 2.显示待支付标签、显示支付按钮
// 3.显示活动进行中标签、显示立即秒杀按钮
// 4.显示已支付标签
// 5.显示支付超时标签
// 6.显示待退款标签
// 7.显示已退款标签
import Serv from './orderListServ';
var regeneratorRuntime = require("../../../../lib/js/runtime-module.js")
import Util from '../../../../utils/util.js'

Page({
   
  /**
   * 页面的初始数据
   */
  data: {
    tabIndex:0, // 当前显示的上方tab栏
    tabBar: { home: '../auction/auction', mine: '../orderList/orderList' },  //底部tab栏设置项
    showTabBur: true,   //控制是否显示底部tab栏(从我的-活动进入不显示,从竞拍活动页进入显示)
    //订单列表状态
    // 1 竞拍未开始 , 2 竞拍中 , 3 待支付 , 4 已支付 , 5 支付超时 , 6 待退款 , 7 已退款
    map: {
      1: {
        statusName: '竞拍未开始',
        statusTagColor: 'tag_blue',
        buttonName: '联系客服',
        buttonStype: '',
      },
      2: {
        statusName: '待支付',
        statusTagColor: 'tag_yellow',
        buttonName: '立即支付',
        buttonStype: 'bg_blue',
      },
      3: {
        statusName: '竞拍中',//状态名称
        statusTagColor: 'tag_yellow',//状态框样式    tag_grey 灰, tag_yellow,黄,tag_blue 蓝,tag_pink 粉红   
        buttonName: '加价',//订单按钮文字
        buttonStype: 'bg_blue',//空白底篮筐，bg_blue为蓝底白字
      },
      4: {
        statusName: '已支付',
        statusTagColor: 'tag_blue',
        buttonName: '联系销售',
        buttonStype: '',
      },
      5: {
        statusName: '支付超时',
        statusTagColor: 'tag_grey',
        buttonName: '联系客服',
        buttonStype: '',
      },
      6: {
        statusName: '待退款',
        statusTagColor: 'tag_pink',
        buttonName: '联系客服',
        buttonStype: '',
      },
      7: {
        statusName: '已退款',
        statusTagColor: 'tag_grey',
        buttonName: '联系客服',
        buttonStype: '',
      }
    },
    //关注列表状态
    // 1 竞拍中(已交报名费) , 2 竞拍中(未支付报名费) , 3 竞拍未开始(未交报名费) , 4 竞拍未开始(已交报名费) , 5 竞拍结束
    mapSec:{
      1: {
        statusName: '竞拍中',//状态名称
        statusTagColor: 'tag_yellow',//状态框样式   tag_grey 灰, tag_yellow,黄,tag_blue 蓝,tag_pink 粉红
        buttonName: '加价',//关注项按钮文字
      },
      2: {
        statusName: '竞拍中',
        statusTagColor: 'tag_yellow',
      },
      3: {
        statusName: '竞拍未开始',
        statusTagColor: 'tag_blue',
      },
      4: {
        statusName: '竞拍未开始',
        statusTagColor: 'tag_blue'
      },
      5: {
        statusName: '竞拍结束',
        statusTagColor: 'tag_grey'
      }
    },
    list: [],  //列表
    endTimeList:[], //倒计时列表
    productDeType: [4, 5, 6, 7],
    productHouseType: [1, 2, 3]
  },
  //切换tab栏
  changeTab:function(e){
    let index = e.currentTarget.dataset.tabindex
    if (this.data.tabIndex === index) {
      return false;
    } else {
      this.setData({
        tabIndex: index
      })
      if (index == 0) {
        this.getActivityList({ orderFlag: 1 },0)
        this.setData({ orderFlag: 1, list: []})
        clearTimeout(this.data.timeOut)
      } else if (index == 1) {
        this.setData({ orderFlag: 2, list: []  })
        this.getActivityList({ orderFlag: 2 },0)
      } else if (index == 2) {
        this.getActivityList({ orderFlag: 3 },0)
        this.setData({ orderFlag: 3, list: []})
        clearTimeout(this.data.timeOut)
      } else if (index == 3) {
        this.getFavoriteList({}, 0)
        this.setData({ orderFlag: 4, list: []})
        clearTimeout(this.data.timeOut)
      }
    }
  },
  // 跳转到详情页
  goDetail:function (e) {
    let id= e.currentTarget.dataset.id,
        orderFlag = this.data.orderFlag
    let item = e.currentTarget.dataset.item
    let order2FLag = item.orderFlag
    if (orderFlag != 4 && order2FLag){
      wx.navigateTo({
        url: `../orderDetail/orderDetail?id=${id}&tabIndex=${this.data.tabIndex}`
      })
    }else{
      let action = e.currentTarget.dataset.action
      let pid = e.currentTarget.dataset.pid
      
      if(action == 3 || action == 4 ){
        wx.navigateTo({
          url: `/subPackages2/pages/auctions/auctionDetail/auctionDetail?id=${pid}&follow=1&action=2`
        })
      }else {
        wx.navigateTo({
          url: `/subPackages2/pages/auctions/auctionDetail/auctionDetail?id=${pid}&follow=1&action=1`
        })
      }
    }
  },
  //订单列表按钮
  toPay(e) {
    let action = e.currentTarget.dataset.action,
        id = e.currentTarget.dataset.id,
      orderid = e.currentTarget.dataset.orderid,
      mobile = e.currentTarget.dataset.mobile,
      phone = e.currentTarget.dataset.phone,
      type = e.currentTarget.dataset.type
    if (action == 1 || action == 5 || action == 6 || action == 7) {
      wx.makePhoneCall({ phoneNumber: phone })
    } else if(action == 3){
      wx.navigateTo({
        url: `/subPackages2/pages/auctions/enterAuction/enterAuction?id=${id}`
      })
    } else if (action == 2){
      if(type==1){
        wx.navigateTo({
          url: `/subPackages2/pages/pay/payment/payment?seckillProductId=${id}&actionType=3`
        })
      }else{
        wx.navigateTo({
          url: `/subPackages2/pages/pay/payment/payment?seckillOrderId=${orderid}&seckillProductId=${id}&actionType=4`
        })
      }
      
    } else if (action == 4){
      wx.makePhoneCall({ phoneNumber: mobile })
    }
  },
  //关注列表按钮
  toNext(e){
    let action = e.currentTarget.dataset.action,
      id = e.currentTarget.dataset.id
    if (action == 1 ){
      wx.navigateTo({
        url: `/subPackages2/pages/auctions/enterAuction/enterAuction?id=${id}`
      })
    } else if (action == 2 || action ==3){
      wx.navigateTo({
        url: `/subPackages2/pages/pay/payment/payment?actionType=3&seckillProductId=${id}`
      })
    }
  },
  //获取竞拍订单列表
  getActivityList: async function (params,isPush){
    let { rows, success, msg, total, pageNo } = await Serv.queryActivityList(params)
    if (success) {
      // this.setData({ endTimeList: [], countDownList: [] })
      //处理返回数据
      let timeList = []
      rows.map(item => {
        let detail = JSON.parse(item.detail)
        item.detail = detail
        //获取支付超时时间
        timeList.push(item.payTimeOut)
      })
      console.log(rows, timeList, this.data.endTimeList)
      if(isPush==0){
        this.setData({ list: rows, total, pageNo, endTimeList: timeList })
      }else{
        let list = this.data.list
        list.push(...rows)
        this.setData({ list: list, total, pageNo, endTimeList: this.data.endTimeList.concat(timeList) })
      }
      if(this.data.orderFlag==2){
        this.countDown()
      }
    }else{
      this.setData({ list: [], endTimeList: [], countDownList: []})
    }
  },
  
  //获取竞拍关注列表
  getFavoriteList :async function (params,isPush) {
    let { success, rows, msg, total, pageNo } = await Serv.queryFavoriteList(params)
    if (success){
      rows.map(item => {
        if (item.startTime && item.startTime) {
          let startTime = item.startTime.substr(0, item.startTime.length - 3),
            endTime = item.endTime.substr(0, item.endTime.length - 3)
          startTime = startTime.replace(/-/g, '.')
          endTime = endTime.replace(/-/g, '.')
          item.startTime = startTime
          item.endTime = endTime
        }
        //根据返回状态判断出关注活动的当前状态(后端负责人:林动)
        let activityStatus = item.activityStatus,  //活动状态 1未开始  2竞拍中   3已结束
          status = item.status,   // 订单状态（1：待支付 2：支付成功 9：已退款）
          type = item.type       // 类型（1：报名费 2：定金）
        if (((type == 1 && status != 1) || (type == 2 && status)) && activityStatus == 2) {
          item.action = 1
        } else if (!type && !status && activityStatus == 2 || type == 1 && status ==1  && activityStatus == 2) {
          item.action = 2
        } else if (!type && !status && activityStatus == 1 || type == 1 && status == 1 && activityStatus == 1) {
          item.action = 3
        } else if (((type == 1 && status != 1) || (type == 2 && status)) && activityStatus == 1) {
          item.action = 4
        } else if (activityStatus == 3) {
          item.action = 5
        }
      })
      console.log(rows)
      if(isPush==0){
        this.setData({ list: rows, total, pageNo })
      }else{
        let list = this.data.list
        list.push(...rows)
        this.setData({ list: list, total, pageNo })
      }
    }else{
      this.setData({ list: [] })
      msg = msg == "null" ? "暂无数据" : msg
      wx.showToast({
        title: msg,
        icon: 'none'
      })
    }

  },

  countDown() {//倒计时函数
    // 获取当前时间，同时得到活动结束时间数组
    let newTime = new Date().getTime();
    let endTimeList = this.data.endTimeList;
    let countDownArr = [];
    // 对结束时间进行处理渲染到页面
    endTimeList.forEach(o => {
      let endTime = Util.dateFromString(o).getTime();
      let obj = null;
      // 如果活动未结束，对时间进行处理
      if (endTime - newTime > 0) {
        let time = (endTime - newTime) / 1000;
        // 获取天、时、分、秒
        let day = parseInt(time / (60 * 60 * 24));
        let hou = parseInt(time % (60 * 60 * 24) / 3600) + (24 * day);
        let min = parseInt(time % (60 * 60 * 24) % 3600 / 60);
        let sec = parseInt(time % (60 * 60 * 24) % 3600 % 60);
        obj = {
          day: this.timeFormat(day),
          hou: this.timeFormat(hou),
          min: this.timeFormat(min),
          sec: this.timeFormat(sec)
        }
      } else {//活动已结束，全部设置为'00'
        obj = {
          day: '00',
          hou: '00',
          min: '00',
          sec: '00'
        }
        clearTimeout(this.data.timeOut)
      }
      countDownArr.push(obj);
      console.log(obj)
    })
    // 渲染，然后每隔一秒执行一次倒计时函数
    this.setData({ countDownList: countDownArr })
    this.data.timeOut = setTimeout(this.countDown, 1000);
  },
  timeFormat(param) {//小于10的格式化函数
    return param < 10 ? '0' + param : param;
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let orderFlag = options.tabIndex ? Number(options.tabIndex) + 1 : 1
    this.setData({ orderFlag, seckillActivityId: options.seckillActivityId||'',tabIndex: options.tabIndex||0})
    if (options.type && options.type == 1) {
      this.setData({ showTabBur: false })
    }
  },
  
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
  
  },
  
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    //显示页面时,获取当前状态栏最新数据列表
    let orderFlag = this.data.orderFlag
    if (orderFlag == 1 || orderFlag ==3) {
      this.getActivityList({ orderFlag: this.data.orderFlag },0)
    } else if (orderFlag ==2){
      this.getActivityList({ orderFlag: this.data.orderFlag },0)
    } else if (orderFlag == 4){
      let params = { }
      this.getFavoriteList({pageNo: 1,pageSize: 10},0)
    }
  },
  
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    //隐藏页面清空计时器
    clearTimeout(this.data.timeOut)
  },
  
  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    //退出页面清空计时器
    clearTimeout(this.data.timeOut)
  },
  
  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    let orderFlag = this.data.orderFlag
    // let { rows, success, msg, total, pageNo } = await Serv.queryActivityList(params),
    if (orderFlag == 1) {
      wx.showNavigationBarLoading()
      this.getActivityList({ orderFlag: this.data.orderFlag }, 0)
      wx.hideNavigationBarLoading() //完成停止加载
      wx.stopPullDownRefresh() //停止下拉刷新
    }
    wx.stopPullDownRefresh() //停止下拉刷新
  },
  
  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
  
  },
  
  /**
   * 用户点击右上角分享
   */
  // onShareAppMessage: function () {
  
  // },
  onReachBottom: function () {
    //上拉列表到底触发分页请求
    let total = Number.parseInt(this.data.total) // 总条数
    let totalPage = 1 // 总页数
    if (total % 10 === 0) {
      totalPage = Number.parseInt(total / 10)
    } else {
      totalPage = Number.parseInt(total / 10) + 1
    }
    let pageNo = Number.parseInt(this.data.pageNo) // 当前页数
    if (pageNo < totalPage && (pageNo + 1) <= totalPage) { // 如果当前条数小于总条数
      if (this.data.orderFlag != 4){
        let pageParams = {
          pageNo: pageNo + 1,
          pageSize: 10,
          orderFlag: this.data.orderFlag
        }
        this.getActivityList(pageParams,1)
      }else{
        let pageParams = {
          pageNo: pageNo + 1,
          pageSize: 10
        }
        this.getFavoriteList(pageParams,1)
      }
      
    }
  }
})
